package com.kaesar.leetcode.LeetCode_051_100;

public class LeetCode_056 {
    public static int[][] merge(int[][] intervals) {
        if (intervals == null || intervals.length == 1) {
            return intervals;
        }
        int length = intervals.length, match = 0, matchFirst, matchSecond;
        boolean[] flag = new boolean[length];

        for (int i = 0; i < length; i++) {
            if (!flag[i]) {
                matchFirst = intervals[i][0];
                matchSecond = intervals[i][1];
                match++;
                for (int j = i + 1; j < length && !flag[j]; j++) {
                    int curFirst = intervals[j][0], curSecond = intervals[j][1];
                    if (((matchFirst >= curFirst && matchFirst <= curSecond) || (matchSecond >= curFirst && matchSecond <= curSecond)) ||
                            ((curFirst >= matchFirst && curFirst <= matchSecond) || (curSecond >= matchFirst && curSecond <= matchSecond))) {
                        // 有交集
                        matchFirst = Math.min(matchFirst, curFirst);
                        matchSecond = Math.max(matchSecond, curSecond);
                        intervals[i][0] = matchFirst;
                        intervals[i][1] = matchSecond;
                        flag[j] = true;
                    }
                }
            }
        }
        if (match == length) {
            return intervals;
        }
        int[][] newIntervals = new int[match][2];
        for (int i = 0, j = 0; i < length; i++) {
            if (!flag[i]) {
                newIntervals[j] = intervals[i];
                j++;
            }
        }
        return merge(newIntervals);
    }

    public static void main(String[] args) {
        int[][] intervals = new int[][]{{1, 4}, {2, 3}};
        for (int[] ints : merge(intervals)) {
            for (int anInt : ints) {
                System.out.print(anInt + " ");
            }
            System.out.println();
        }
    }
}
